package com.lzw.breezeNovel.webApp.service.impl.comic;


import com.lzw.breezeNovel.common.exception.BaseException;
import com.lzw.breezeNovel.common.login.LoginUser;
import com.lzw.breezeNovel.common.login.LoginUserHolder;
import com.lzw.breezeNovel.common.result.ResultCodeEnum;
import com.lzw.breezeNovel.model.entity.pojo.comic.Comic;
import com.lzw.breezeNovel.model.entity.pojo.user.UserInfo;
import com.lzw.breezeNovel.model.entity.query.PaginationResultQuery;
import com.lzw.breezeNovel.model.enums.comic.ComicStatus;
import com.lzw.breezeNovel.webApp.mapper.comic.ComicMapper;
import com.lzw.breezeNovel.webApp.mapper.user.UserInfoMapper;
import com.lzw.breezeNovel.webApp.service.comic.ComicService;
import com.lzw.breezeNovel.webApp.vo.comic.ComicVo;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.webApp.service.impl.comic
 * @date 2025/3/15
 * @description 漫画的服务类
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class ComicServiceImpl implements ComicService {

    /**
     * 漫画的mapper
     */
    @Autowired
    private ComicMapper comicMapper;
    /**
     * 注入用户mapper
     */
    @Autowired
    private UserInfoMapper userMapper;

    /**
     * 获取漫画排行榜
     *
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public PaginationResultQuery<ComicVo> getRank(Integer pageNo, Integer size,String like) {
        // 获取用户id
        Long id = getUserId();
        //计算分页方法
        Integer start = getStart(pageNo, size);
        // 查询漫画总数
        Long count = comicMapper.selectCount();

        // 如果没有数据，直接返回空结果
        if (count == 0) {
            return new PaginationResultQuery<>(0, size, pageNo, 0, new ArrayList<>());
        }
        // 查询分页数据
        List<Comic> comicRank = comicMapper.getComicRank(start, size, like, id);

        // 将Comic对象转换为ComicVo对象
        List<ComicVo> comicVoList = copy(comicRank);

        // 返回分页结果
        return new PaginationResultQuery<>(
                count.intValue(),
                size,
                pageNo,
                comicRank.size(),
                comicVoList
        );
    }

    /**
     * 获取vip漫画
     * @param pageNo
     * @param size
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public PaginationResultQuery<ComicVo> getVip(Integer pageNo, Integer size) {
        // 获取用户id
        Long id = getUserId();
        //计算分页数据
        Integer start = getStart(pageNo, size);
        //查询漫画总数
        Long count = comicMapper.selectCount();
        //如果没有数据，直接返回空结果
        if (count == 0) {
            return new PaginationResultQuery<>(0, size, pageNo, 0, new ArrayList<>());
        }
        //查询分页数据
        List<Comic> vipComic = comicMapper.getVipComic(start, size,id);
        //将Comic对象转换为ComicVo对象
        List<ComicVo> comicVoList = copy(vipComic);
        // 返回分页结果
        return new PaginationResultQuery<>(
                count.intValue(),
                size,
                pageNo,
                vipComic.size(),
                comicVoList
        );
    }

    /**
     * 获取免费漫画
     * @param pageNo
     * @param size
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public PaginationResultQuery<ComicVo> getFree(Integer pageNo, Integer size) {
        // 获取用户id
        Long id = getUserId();
        //计算分页数据
        Integer start = getStart(pageNo, size);
        //查询漫画总数
        Long count = comicMapper.selectCount();
        //如果没有数据，直接返回空结果
        if (count == 0) {
            return new PaginationResultQuery<>(0, size, pageNo, 0, new ArrayList<>());
        }
        //查询分页数据
        List<Comic> freeComic = comicMapper.getFreeComic(start, size,id);
        //将Comic对象转换为ComicVo对象
        List<ComicVo> comicVoList = copy(freeComic);
        // 返回分页结果
        return new PaginationResultQuery<>(
                count.intValue(),
                size,
                pageNo,
                freeComic.size(),
                comicVoList
        );

    }

    /**
     * 获取最新漫画
     * @param pageNo
     * @param size
     * @return
     */
    @Override
    public PaginationResultQuery<ComicVo> getNew(Integer pageNo, Integer size) {
        //计算分页
        Integer start = getStart(pageNo, size);
        //查询漫画总数
        Long count = comicMapper.selectCount();
        //如果没有数据，直接返回空结果
        if (count == 0) {
            return new PaginationResultQuery<>(0, size, pageNo, 0, new ArrayList<>());
        }
        //查询分页数据
        List<Comic> newComic = comicMapper.getNewComic(start, size);
        //将Comic对象转换为ComicVo对象
        List<ComicVo> comicVoList = copy(newComic);
        // 返回分页结果
        return new PaginationResultQuery<>(
                count.intValue(),
                size,
                pageNo,
                newComic.size(),
                comicVoList
        );
    }

    /**
     * 进行漫画搜索
     * @param pageNo
     * @param size
     * @param keyword
     * @return
     */
    @Override
    public PaginationResultQuery<ComicVo> search(Integer pageNo, Integer size, String keyword) {
        //计算分页
        Integer start = getStart(pageNo, size);
        //获取用户id
        Long id = getUserId();
        //查询漫画总数
        Long count = comicMapper.selectCountByKeyword(keyword);
        //如果没有数据，直接返回空结果
        if (count == 0) {
            return new PaginationResultQuery<>(0, size, pageNo, 0, new ArrayList<>());
        }
        //查询分页数据
        List<Comic> searchComic = comicMapper.searchComic(start, size, keyword,id);
        //将Comic对象转换为ComicVo对象
        List<ComicVo> comicVoList = copy(searchComic);
        return new PaginationResultQuery<>(
                count.intValue(),
                size,
                pageNo,
                comicVoList.size(),
                comicVoList
        );
    }

    /**
     * 获取分类漫画
     * @param pageNo
     * @param size
     * @param typeId
     * @return
     */
    @Override
    public PaginationResultQuery<ComicVo> getType(String type,Integer pageNo, Integer size,Integer id) {
        //计算分页
        Integer start = getStart(pageNo, size);
        //查询数量
        int count = comicMapper.selectCountByType(type);
        //如果没有数据，直接返回空结果
        if (count == 0) {
            return new PaginationResultQuery<>(0, size, pageNo, 0, new ArrayList<>());
        }
        //查询分页数据
        List<Comic> typeComic = comicMapper.getTypeComic(start, size, type,id);
        //将Comic对象转换为ComicVo对象
        List<ComicVo> comicVoList = copy(typeComic);
        return new PaginationResultQuery<>(
                count,
                size,
                pageNo,
                comicVoList.size(),
                comicVoList
        );
    }

    /**
     * 更新漫画的播放了
     * @param comicId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(Long comicId) {
       //更新播放了
       comicMapper.updatePlayCount(comicId);
    }


    /**
     * 计算分页数据
     */
    @NotNull
    private Integer getStart(Integer pageNo, Integer size) {
        // 对分页参数进行校验，使用Optional简化代码
        pageNo = Optional.ofNullable(pageNo).orElse(1);
        size = Optional.ofNullable(size).orElse(10);
        pageNo = Math.max(pageNo, 1);
        size = Math.max(size, 1);
        return (pageNo - 1) * size;
    }

    /**
     * 获取用户id
     * @return
     */
    private Long getUserId() {
        //从当前线程里面回去用户信息
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //判断是否为空
        if (loginUser == null) {
            throw new BaseException(ResultCodeEnum.  APP_LOGIN_AUTH);
        }
        String phone = loginUser.getPhone();
        UserInfo userInfo = userMapper.selectByPhone(phone);
        return userInfo.getUserId();
    }

    /**
     * 对于漫画对象进行拷贝
     */
    @Nullable
    @Contract(pure = true)
    private List<ComicVo> copy(@NotNull List<Comic> comicList){
       return comicList.stream().map(comic -> {
            //创建ComicVo对象
            ComicVo comicVo = new ComicVo();
            //拷贝属性
            BeanUtils.copyProperties(comic,comicVo);
            //获取漫画的状态
            Integer status = comic.getStatus();
            //根据状态获取描述
            String statusDesc = ComicStatus.getDesc(status);
            //设置状态描述
            comicVo.setStatus(statusDesc);
            //判断是否要收费
             String like = comic.getFree() == 0 ? "免费" : "付费";
             comicVo.setFree(like);
            return comicVo;
        }).collect(Collectors.toList());
    }
}
